import axios from 'axios';
import store from '@/store/index'
import { Message } from 'element-ui';
import router from '@/router/index'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token;
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code !== 10000) {
      Message.error(response.data.msg)
      return Promise.reject(response.data)
    } else {
      return response.data
    }

  },
  error => {
    //判断token是否失效
    if (error.response.status === 401) {
      //token已过期,清空token
      store.commit('user/removeToken');
      router.push('/login');
    }
    //统一错误处理
    Message.error(error.response.data.msg)
    return Promise.reject(error);
  }
)

export default service
